package controllers

import play.api._
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import play.api.db.slick._
import play.api.Play.current
import views._
import models._

object Groups extends Controller {

  val groupForm = Form(
    mapping(
      "id" -> optional(longNumber),
      "name" -> nonEmptyText,
      "homePage" -> optional(text)
    )(Group.apply)(Group.unapply)
  )

  val Home = Redirect(routes.Groups.list)

  def list = DBAction { implicit rs =>
     Ok(html.group.list(GroupDAO.list))
  }
  
 /**
   * Display the 'new group form'.
   */
  def create = DBAction { implicit rs =>
     Ok(html.group.admin(groupForm))
  }

  /**
   * Display the 'edit form' of an existing Group
   *
   * @param id Id of the group to edit
   */
  def edit(id: Long) = DBAction { implicit rs =>
    GroupDAO.findById(id).map { group =>
       Ok(html.group.admin(groupForm.fill(group)))
     }.getOrElse(NotFound)
  }

  /**
   * Handle the form submission 
   *
   */
  def submit = DBAction { implicit rs =>
    groupForm.bindFromRequest.fold(
      formWithErrors => BadRequest(html.group.admin(formWithErrors)),
      group => {
        if (group.id.isDefined) {
          GroupDAO.update(group)
        } else {
          GroupDAO.insert(group)
        }

        Home.flashing("success" -> "Group %s has been saved".format(group.name))
      }
    )
  }

  /**
   * Handle group deletion
   */
  def delete(id: Long) = DBAction { implicit rs =>
    GroupDAO.delete(id)
    Home.flashing("success" -> "Group has been deleted")
  }
  
}